﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.interfaces;
using System.Xml;
using umbraco.cms.businesslogic.web;
using AutoFolders.Providers;
using umbraco;

namespace AutoFolders
{
    public class NotFoundHandler : INotFoundHandler
    {
        private int m_redirectID = -1;
        private bool m_cacheUrl = true;

        #region INotFoundHandler Members

        public bool Execute(string url)
        {
            bool m_success = false;
            string tempUrl = url;
            if (tempUrl.Length > 0)
            {
                if (tempUrl.Substring(0, 1) == "/")
                    tempUrl = tempUrl.Substring(1, tempUrl.Length - 1);

                // Check for domain
                string currentDomain = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
                string prefixXPath = "";
                if (Domain.Exists(currentDomain))
                {
                    prefixXPath = string.Format("//node [@id = '{0}']", Domain.GetRootFromDomain(currentDomain));
                    m_cacheUrl = false;
                }

                // Check IFolderProviders for 
                string pageUrl = url.Substring(url.LastIndexOf("/"));

                if (pageUrl.Substring(0, 1) == "/")
                    pageUrl = pageUrl.Substring(1, pageUrl.Length - 1);


                string theParentUrl = url.Substring(0, url.LastIndexOf("/"));
                //string parentNodeName = theParentUrl.Substring(theParentUrl.LastIndexOf("/") + 1).ToLower();
                IFolderProvider folderProvider = AutoFolderSettings.Instance.GetFolderProviderByParentUrl(theParentUrl);

                if (folderProvider != null)
                {
                    string parentUrlXPath = requestHandler.CreateXPathQuery(theParentUrl, true);
                    XmlNode parentNode = content.Instance.XmlContent.SelectSingleNode(parentUrlXPath);

                    if (parentNode != null)
                    {
                        XmlNode redir = content.Instance.XmlContent.SelectSingleNode("//node[@id='" + parentNode.Attributes.GetNamedItem("id").Value + "']//node [@urlName = '" + pageUrl.Replace(".aspx", string.Empty).ToLower() + "']");
                        
                        if (redir != null)
                        {
                            m_redirectID = int.Parse(redir.Attributes.GetNamedItem("id").Value);
                            m_success = true;
                        }
                    }
                }
            }
            return m_success;
        }

        public bool CacheUrl
        {
            get { return m_cacheUrl; }
        }

        public int redirectID
        {
            get
            {
                return m_redirectID;
            }
        }

        #endregion
    }
}
